﻿
using AllanXingCommonLibrary;
using cnBlogLibrary;
using cnBlogs.Common;
using cnBlogs.DataModel;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace cnBlogs.ViewModel
{
    public class NewsInfoViewModel : GetFeedsBase
    {
        private GeneratorIncrementalLoadingClass<NewsInfo> _newsInfolist;

        public GeneratorIncrementalLoadingClass<NewsInfo> NewsInfolist
        {
            get { return _newsInfolist; }
            set { this.SetProperty(ref  _newsInfolist, value); }
        }
        protected List<NewsInfo> _rangeList = new List<NewsInfo>();

        protected uint _pageCount;

        public NewsInfoViewModel()
        {
            NewsInfolist = new GeneratorIncrementalLoadingClass<NewsInfo>(200, IncrementalM);
        }

        protected virtual async Task<List<NewsInfo>> IncrementalM(uint pageCount)
        {
            _pageCount = pageCount;
            await GetResource();
            return this._rangeList;
        }

        protected override void Parse(string feed)
        {
            _rangeList.Clear();
            MatchCollection matches = Regex.Matches(feed, "<div class=\"post_item\">.*?<div class=\"post_item_body news_body\".*?></div>");
            NewsInfolist.HasCount = !(matches.Count < 20);
            foreach (Match item in matches)
            {
                NewsInfo newsinfo = new NewsInfo();
                string regex_news = item.Value;
                GroupCollection gp = Regex.Match(regex_news, "<h3><a class=\"titlelnk\" href=\"(?<link>.*?)\".*?>(?<title>.*?)</a></h3>").Groups;
                newsinfo.Title = gp["title"].Value;
                newsinfo.Link = gp["link"].Value;
                GroupCollection gp1 = Regex.Match(regex_news, "<p class=\"post_item_summary\">(<a href=\"(?<topiclink>.*?)\".*?><img class=\"news_topic\" src=\"(?<imageurl>.*?)\".*?/></a>)?(?<Overview>.*?)</p>").Groups;
                newsinfo.Overview = gp1["Overview"].Value.Replace("\r", string.Empty).Trim();
                newsinfo.topicLink = gp1["topiclink"].Value;
                newsinfo.newsPicture = gp1["imageurl"].Value;
                GroupCollection gpwriteraAndtime = Regex.Match(regex_news, "<a href=\".*?\" class=\"lightblue\">(?<writer>.*?)</a> *(?<PublishTime>.*?) *<span class=\"article_comment\">").Groups;
                newsinfo.PublishTime = gpwriteraAndtime["PublishTime"].Value.TrimStart();
                _rangeList.Add(newsinfo);
            }

        }

        protected override string GetUrl()
        {
            string url = AppResource.cnBlogsUlr;
            url = url + "news/" + _pageCount + "/";
            return url;
        }
    }
}
